package com.pan.insist.dao;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.pan.insist.cache.MybatisRedisCache;
import com.pan.insist.model.RoleModel;
import org.apache.ibatis.annotations.CacheNamespace;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.SelectKey;

import java.util.List;
import java.util.Set;

/**
 * <p>
 * 角色信息表 Mapper 接口
 * </p>
 *
 * @author kaiji
 * @since 2019-08-17
 */
@Mapper
@CacheNamespace(implementation= MybatisRedisCache.class, eviction= MybatisRedisCache.class)
public interface RoleMapper extends BaseMapper<RoleModel> {

    /**
     * 根据角色查询权限地址
     *
     * @param codes
     *      角色代码集合
     * @return
     *      权限地址集合
     */
    @Select("<script>select b.url from t_role as a, t_menu as b, t_menu_role as c " +
            "where a.id = c.role_id and b.id = c.menu_id and a.code in " +
            "<foreach collection=\"codes\" item=\"code\" index=\"index\" open=\"(\" close=\")\" separator=\",\"> " +
            "#{code}" +
            "</foreach>" +
            "</script>")
    Set<String> getUrlByRole(@Param("codes") List<String> codes);

    /**
     * 根据角色名称或代码查询是否存在数据
     *
     * @param roleModel
     *      角色对象
     * @return  角色对象
     */
    @Select("<script>" +
            "select a.* from t_role as a where (a.name = #{name} or a.code = #{code}) " +
            "<if test='id != null'>" +
            "and a.id != #{id}" +
            "</if>" +
            "</script>")
    RoleModel getExistByFilter(RoleModel roleModel);

    /**
     * 根据角色删除角色与权限的关系
     *
     * @param roleId
     *      角色主键
     */
    @Delete("delete from t_menu_role where role_id = #{roleId}")
    void deleteByRoleId(@Param("roleId") String roleId);

    /**
     * 保存角色与权限
     *
     * @param roleId
     *      角色主键ID
     * @param purviewId
     *      权限列表
     */
    @SelectKey(keyProperty = "id",resultType = String.class, before = true,
            statement = "select replace(uuid(), '-', '')")
    @Options(keyProperty = "id", useGeneratedKeys = true)
    @Insert("<script>insert into t_menu_role(id, menu_id, role_id, create_date) values " +
            "(#{id}, #{purviewId}, #{roleId}, now()) </script>")
    void saveRoleAndPurview(@Param("roleId") String roleId, @Param("purviewId") String purviewId);


    /**
     * 根据用户查询用户相关角色
     *
     * @param userId
     *      用户主键
     * @return 自己的角色列表
     */
    @Select("<script>select b.* from t_user as a, t_role as b, t_user_role as c where a.id = c.user_id " +
            "and b.id = c.role_id and a.id = #{userId}</script>")
    List<RoleModel> getUser(@Param("userId") String userId);
}
